package xj.graph2d.command;

import xj.graph2d.Arrow;
import xj.graph2d.ArrowAttr;
import xj.graph2d.DrawShape;
import xj.graph2d.OpenShape;
import xj.graph2d.SimpleDrawDocument;
import xj.graph2d.SimpleDrawView;

public class SetArrowsCommand extends DeltaCommand {

  public SetArrowsCommand(SimpleDrawView view, SimpleDrawDocument doc,
      DrawShape shape) {
    super(view, doc, shape);
    if (shape instanceof OpenShape) {
      oshape = (OpenShape) shape;
      Arrow head = oshape.getHeadArrow();
      Arrow tail = oshape.getTailArrow();
      if (tail != null) {
	startTail = new ArrowAttr();
	tail.copyArrowAttr(startTail);
      }
      if (head != null) {
	startHead = new ArrowAttr();
	head.copyArrowAttr(startHead);
      }
    }
  }

  @Override
  protected void forward() {
    if (oshape != null) {
      oshape.setTailArrow(endTail);
      oshape.setHeadArrow(endHead);
      shape.calculateBounds();
    }
  }

  @Override
  protected void backward() {
    if (oshape != null) {
      if (!undone) {
	Arrow head = oshape.getHeadArrow();
	Arrow tail = oshape.getTailArrow();
	if (tail != null) {
	  endTail = new ArrowAttr();
	  tail.copyArrowAttr(endTail);
	}
	if (head != null) {
	  endHead = new ArrowAttr();
	  head.copyArrowAttr(endHead);
	}
	undone = true;
      }
      oshape.setTailArrow(startTail);
      oshape.setHeadArrow(startHead);
      shape.calculateBounds();
    }
  }

  protected OpenShape oshape;

  protected boolean undone = false;

  protected ArrowAttr startTail = null, startHead = null;

  protected ArrowAttr endTail = null, endHead = null;

}
